#include "progressbar.hpp"

namespace MFUI{
	ProgressBar::ProgressBar(SDL_Color back,SDL_Color bar,float v,bool edit):edit(edit),
	background(back),barcolor(bar){
		if(0.F<=v&&v<=1.F)value=v;else value=1.F;
	}
	float ProgressBar::getvalue()const{return value;}
	void ProgressBar::setvalue(float v){
		if(0.F<=v&&v<=1.F){
			value=v;
			redraw=true;
			changed();
			notifyparent();
		}
	}
	void ProgressBar::setbackground(SDL_Color c){
		if(*(Uint32*)&background!=*(Uint32*)&c){
			background=c;
			redraw=true;
			notifyparent();
		}
	}
	void ProgressBar::setbarcolor(SDL_Color c){
		if(*(Uint32*)&barcolor!=*(Uint32*)&c){
			barcolor=c;
			redraw=true;
			notifyparent();
		}
	}
	void ProgressBar::setedit(bool v){
		if(edit!=v){
			edit=v;
			notifyparent();
		}
	}
	SDL_Color ProgressBar::getbackground()const{return background;}
	SDL_Color ProgressBar::getbarcolor()const{return barcolor;}
	void ProgressBar::changed(){}
	void ProgressBar::draw(Renderer* r,bool updatecache){
		CacheNode::_draw(r,updatecache);
		auto w=rect.w*0.05F,h=rect.h*0.05F;
		SDL_FRect _{rect.x+w,rect.y+h,(rect.w-w-w)*value,rect.h-h-h};
		auto a=background.a,ba=barcolor.a;
		if(edit){
			switch(getstate()){
				case state_released:break;
				case state_on:a>>=1,ba>>=1;break;
				case state_pressed:a>>=2,ba>>=2;break;
			}
		}
		r->setdrawcolor({background.r,background.g,background.b,a});
		r->fillrectF(&rect);
		r->setdrawcolor({barcolor.r,barcolor.g,barcolor.b,ba});
		r->fillrectF(&_);
		redraw=false;
	}
	void ProgressBar::mouseentered(Window* w){
		if(edit)redraw=true,notifyparent();
	}
	void ProgressBar::mouseexited(Window* w){
		if(edit)redraw=true,notifyparent();
	}
	ProgressBar::~ProgressBar(){}
	void ProgressBar::_released(Window* w,SDL_FPoint p){redraw=true;notifyparent();}
	void ProgressBar::_losefocus(Window* w){redraw=true;notifyparent();}
	void ProgressBar::_pressed(Window* w,SDL_FPoint p){
		if(edit){
			redraw=true;
			mousemove(w,p);
		}
	}
	void ProgressBar::mousemove(Window* w,SDL_FPoint p){
		if(getstate()==state_pressed){
			auto w=rect.w*0.05F;
			if(p.x<rect.x+w){
				setvalue(0.F);
				return;
			}
			auto t=rect.w-w;
			if(p.x>rect.x+t){
				setvalue(1.F);
				return;
			}
			setvalue((p.x-rect.x-w)/(t-w));
			return;
		}
	}
}